package cn.kshost.zqyg.product.helper;

import cn.kshost.zqyg.model.entity.product.Category;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class CategoryTreeHelper {
    public static List<Category> buildTree(List<Category> categories) {
        List<Category> tree = new ArrayList<Category>();
        for (Category category : categories) {
            if (category.getParentId() == 0) {
                //构建节点(传入列表和当前根节点)
               Category nodeCategory =  buildNode(category,categories);
                //添加节点
                tree.add(nodeCategory);
            }
        }
        return tree;
    }

    public static Category buildNode(Category category, List<Category> categories) {
        category.setChildren(new LinkedList<Category>());
        for (Category child : categories) {
            if (child.getParentId() == category.getId()) {
                category.getChildren().add(buildNode(child,categories));
            }
        }
        return category;
    }
}
